/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


server_root = 'http://localhost/SSOT_SAT/trunk/';
  
	$(function() {
                
                charts = [];
                containerId = 0;
                containerCounter = 0;
                indexes = [];
                yAxisLabels = [];
                creating = false;
                YAxisLabelsCounter = 0;
                
                //Jquery UI Inizialitation
                $(document).tooltip();
                $("input[type=checkbox]").button();
                $("#menu").tabs();
                $(".eliminar:button").button();
                
                $.ajax({
                                  url: server_root+"date_bd.php",
                                  async: false,
                                  success: function (data) {
                                    $("#date_bd").text(data);
                                  }
                                });
                
                $("#informe_grid").jqGrid({
                        url:server_root+'load_tabla_informe.php',
                        datatype: "json",
                        colNames:['ID','Fecha', 'Nombre','Parametros','Autor','Comentario'],
                        colModel:[
                                {name:'id',index:'id', width:55,editable:false,editoptions:{readonly:true,size:10}},
                                {name:'date',index:'date', width:130,editable:false,editoptions:{size:10}},
                                {name:'name',index:'name',width:250,editable:true,editoptions:{size:25}},
                                {name:'params',index:'params',width:200,editable:false,editoptions:{size:25}},
                                {name:'author',index:'author',width:80,editable:false,editoptions:{size:25}},
                                {name:'comment',index:'comment',width:500, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"15",cols:"100"}}		
                        ],
                        rowNum:10,
                        reccount: 10,
                        rowList:[10,20,30],
                        pager: '#pagernav1',
                        sortname: 'id',
                        sortable:true,
                        loadonce:true,
                    viewrecords: true,
                    sortorder: "desc",
                    multiselect: true,
                    caption:"Informes",
                    editurl:"update_tabla_informe.php",
                        height:280
                });
                
                $("#informe_grid")
                    .navGrid('#pagernav1',{edit:false,add:false,del:false,search:false,refresh:false})
                    .navButtonAdd('#pagernav1',{
                       caption:"Borrar", 
                       buttonicon:"ui-icon-trash", 
                       onClickButton: function(){ 
                         
                        var gr = jQuery("#informe_grid").jqGrid('getGridParam','selrow');
                        if( gr != null ) jQuery("#informe_grid").jqGrid('delGridRow',gr,{top:300, left:580, width: 280,reloadAfterSubmit:true});
                        else alert("Por favor seleccione un informe");
                        
                       }, 
                       position:"first"
                    }) .navButtonAdd('#pagernav1',{
                       caption:"Actualizar", 
                       buttonicon:"ui-icon-refresh", 
                       onClickButton: function(){ 
                           $("#informe_grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');
                       }, 
                       position:"last"
                    }).navButtonAdd('#pagernav1',{
                       caption:"Editar",
                       buttonicon:"ui-icon-pencil", 
                       onClickButton: function(){ 
                         var gr = $("#informe_grid").jqGrid('getGridParam','selrow');
                            if( gr != null ) $("#informe_grid").jqGrid('editGridRow',gr,{top:150, left:300,width:1000,height:450,reloadAfterSubmit:false,closeAfterEdit:true});
                            else alert("Por favor seleccione un informe");
                       }, 
                       position:"first"
                    }).navButtonAdd('#pagernav1',{
                       caption:"Ver", 
                       buttonicon:"ui-icon-document", 
                       onClickButton: function(){ 
                            
                            var id = jQuery("#informe_grid").jqGrid('getGridParam','selrow');
                            if (id){
                                        var ret = jQuery("#informe_grid").jqGrid('getRowData',id);
                                        //alert("id="+ret.id);
                                        var dataString = 'id='+ret.id;
                                    
                                        $.ajax({
                                               type: 'POST',
                                               data: dataString,
                                               url: server_root+"pdf_informe.php",
                                               async: false,
                                               success: function(data){
                                                   pdfURL = data;
                                                   //alert(imageURL);
                                                   window.open(pdfURL, '_blank', 'fullscreen=yes')
                                                }
                                            });
                                    }
                            else
                            { alert("Por favor seleccione un informe");}
                            
                       }, 
                       position:"first"
                    })
                    .navButtonAdd('#pagernav1',{
                       caption:"Informe Final", 
                       buttonicon:"ui-icon-note", 
                       onClickButton: function(){
                           informes = jQuery("#informe_grid").jqGrid('getGridParam','selarrrow');
                           if (informes != ''){
                               $( "#dialog-form-informe_final" ).dialog( "open" );
                           }
                           else{
                               alert("Por favor seleccione un informe");
                           }
                       }, 
                       position:"last"
                    });
                    
                    
                    $("#informe_final_grid").jqGrid({
                        url:server_root+'load_tabla_informe_final.php',
                        datatype: "json",
                        colNames:['ID','Fecha', 'Nombre','Parametros','Autor','Informes','Comentario'],
                        colModel:[
                                {name:'id',index:'id', width:55,editable:false,editoptions:{readonly:true,size:10}},
                                {name:'date',index:'date', width:130,editable:false,editoptions:{size:10}},
                                {name:'name',index:'name',width:250,editable:true,editoptions:{size:25}},
                                {name:'params',index:'params',width:200,editable:false,editoptions:{size:25}},
                                {name:'author',index:'author',width:80,editable:false,editoptions:{size:25}},
                                {name:'reports',index:'reports',width:80,editable:true,editoptions:{size:25}},
                                {name:'comment',index:'comment',width:440, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"15",cols:"100"}}		
                        ],
                        rowNum:10,
                        reccount: 10,
                        rowList:[10,20,30],
                        pager: '#pagernav2',
                        sortname: 'id',
                        sortable:true,
                        loadonce:true,
                        hiddengrid: true,
                    viewrecords: true,
                    sortorder: "desc",
                    multiselect: false,
                    caption:"Informes Finales",
                    editurl:"update_tabla_informe_final.php",
                        height:280
                });
                
                $("#informe_final_grid")
                    .navGrid('#pagernav2',{edit:false,add:false,del:false,search:false,refresh:false})
                    .navButtonAdd('#pagernav2',{
                       caption:"Borrar", 
                       buttonicon:"ui-icon-trash", 
                       onClickButton: function(){ 
                         
                        var gr = jQuery("#informe_final_grid").jqGrid('getGridParam','selrow');
                        if( gr != null ) jQuery("#informe_final_grid").jqGrid('delGridRow',gr,{top:300, left:580, width: 280,reloadAfterSubmit:true});
                        else alert("Por favor seleccione un informe");
                        
                       }, 
                       position:"first"
                    }) .navButtonAdd('#pagernav2',{
                       caption:"Actualizar", 
                       buttonicon:"ui-icon-refresh", 
                       onClickButton: function(){ 
                           $("#informe_final_grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');
                       }, 
                       position:"last"
                    }).navButtonAdd('#pagernav2',{
                       caption:"Editar",
                       buttonicon:"ui-icon-pencil", 
                       onClickButton: function(){ 
                         var gr = $("#informe_final_grid").jqGrid('getGridParam','selrow');
                            if( gr != null ) $("#informe_final_grid").jqGrid('editGridRow',gr,{top:150, left:300,width:1000,height:450,reloadAfterSubmit:false,closeAfterEdit:true,
                                afterSubmit : function(response, postdata){ 
                                    if (response.responseText == '0'){
                                        return [false,'Error: Alguno de los identificadores es incorrecto',] 
                                    }else
                                        return [true,,]

                            }});
                            else alert("Por favor seleccione un informe");
                       }, 
                       position:"first"
                    }).navButtonAdd('#pagernav2',{
                       caption:"Ver", 
                       buttonicon:"ui-icon-document", 
                       onClickButton: function(){ 
                            
                            var id = jQuery("#informe_final_grid").jqGrid('getGridParam','selrow');
                            if (id){
                                        var ret = jQuery("#informe_final_grid").jqGrid('getRowData',id);
                                        //alert("id="+ret.id);
                                        var dataString = 'id='+ret.id;
                                    
                                        $.ajax({
                                               type: 'POST',
                                               data: dataString,
                                               url: server_root+"pdf_informe_final.php",
                                               async: false,
                                               success: function(data){
                                                   pdfURL = data;
                                                   window.open(pdfURL, '_blank', 'fullscreen=yes')
                                                }
                                            });
                                    }
                            else
                            { alert("Por favor seleccione un informe");}
                            
                       }, 
                       position:"first"
                    });
  
                $( "#dialog-form-informe" ).dialog({
                                        autoOpen: false,
                                        height: 300,
                                        width: 375,
                                        modal: true,
                                        buttons: {
                                            "Crear": function() {
                                                dataString = "nombre="+$("#nombre_informe").val()+"&autor="+$("#user").val()+"&comentario="+comentario+"&imagen="+imagen+"&parametros="+parametros+"&oper=add";
                                                $.ajax({
                                                       type: 'POST',
                                                       data: dataString,
                                                       url: server_root+'update_tabla_informe.php',
                                                       async: true,
                                                       success: function(data){
                                                            $("#informe_grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');
                                                            $( "#nombre_informe" ).val("");
                                                            $( "#dialog-form-informe" ).dialog( "close" );
                                                        }
                                                    });
                                            },
                                            "Cancelar": function() {
                                                $( this ).dialog( "close" );
                                            }
                                        },
                                        close: function() {
                                            allFields.val( "" ).removeClass( "ui-state-error" );
                                        }
                                    });
                
                $( "#dialog-form-informe_final" ).dialog({
                                        autoOpen: false,
                                        height: 350,
                                        width: 500,
                                        modal: true,
                                        buttons: {
                                            "Crear": function() {
                                               dataString = "nombre="+$("#nombre_informe_final").val()+"&autor="+$("#user").val()+"&informes="+informes+"&comentario="+$("#comment_informe_final").val()+"&oper=add";
                                                $.ajax({
                                                       type: 'POST',
                                                       data: dataString,
                                                       url: server_root+'update_tabla_informe_final.php',
                                                       async: true,
                                                       success: function(data){
                                                            $("#informe_final_grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');
                                                            $( "#nombre_informe_final" ).val("");
                                                            $( "#comment_informe_final" ).val("");
                                                            $( "#dialog-form-informe_final" ).dialog( "close" );
                                                        }
                                                    });
                
                                            },
                                            "Cancelar": function() {
                                                $( this ).dialog( "close" );
                                            }
                                        },
                                        close: function() {
                                            allFields.val( "" ).removeClass( "ui-state-error" );
                                        }
                                    });
                
                
                
                $(".sistema").click(function(){

                    $("#"+$(this).attr("id").toString()+"_p").toggle();
                    $("#"+$(this).attr("id").toString()+"_s").toggle();
                    $("#"+$(this).attr("id")+"_p .param").removeAttr('checked');
                    $("#"+$(this).attr("id")+"_p .param").button('refresh');
                    $("#"+$(this).attr("id")+"_s .shortcut").removeAttr('checked');
                    $("#"+$(this).attr("id")+"_s .shortcut").button('refresh');
                });
            
                $(".shortcut").click(function(){
                    if ($("."+$(this).attr("id")+":input[type=checkbox]:checked").length > 0){
                        
                        $("."+$(this).attr("id")).removeAttr('checked');
                        $(this).removeAttr('checked');
                        $("."+$(this).attr("id")).button('refresh');
                        $(this).button('refresh');
                    }
                    else{
                         $("."+$(this).attr("id")).attr('checked','checked');
                         $("."+$(this).attr("id")).button('refresh');
                    }
                });
                
                $(".eliminar").click( function(){  
                    $('#'+$(this).attr("value").toString()+"_param").hide();
                    $('#'+$(this).attr("value")).removeAttr('checked');
                    $('#'+$(this).attr("value")).button('refresh'); // will check the checkbox with id check1
                    
                    if ($(".param:input[type=checkbox]:checked").length == 0)
                    {
                        $("#fecha").hide();
                        $("#modo").hide();
                    }
                });
 
                $("#variables_a").click(function(){
                   $("#wrapper").css("height","100%"); 
                   $("#menu").css("height","94%");
                });
 
                //Inicio Conf_Graf Click
               
                $("#conf_grafico_a").click(function(){
                    
                    $("#wrapper").css("height","100%");
                    $("#menu").css("height","94%");

                    $(".param:input[type=checkbox]").each(function()
                    {
                        if ($('#'+$(this).attr('id')).is(":checked")){
                            $('#'+$(this).attr('id')+'_param').show();
                        }
                        else{
                             $('#'+$(this).attr('id')+'_param').hide();
                        }
                        
                    });
                   
                   
                   if ($(".param:input[type=checkbox]:checked").length > 0)
                    {
                        
                        $( "#desde" ).datepicker({
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 1,
                        dateFormat: 'yy-mm-dd',
			onSelect: function( selectedDate ) {
			$( "#hasta" ).datepicker( "option", "minDate", selectedDate );
                        }
                        });
                        
                        $( "#hasta" ).datepicker({
                        defaultDate: "+1w",
                        changeMonth: true,
                        numberOfMonths: 1,
                        dateFormat: 'yy-mm-dd',
                        onSelect: function( selectedDate ) {
                        $( "#desde" ).datepicker( "option", "maxDate", selectedDate );
                        }
                        });
                        $("#advertencia_conf").hide();
                        $("#fecha").show();
                        $("#modo").show();
                        }
                    else
                        {
                        $("#fecha").hide();
                        $("#modo").hide();
                        $("#advertencia_conf").show();
                        }
                        
                  $("input:radio[name=modo]").attr("disabled",false);
                  
                  $(".tipo:input[type=radio]:checked:visible").each(function(){
                        
                        if ($(this).attr('value') == "SPV"){
                            $("#normal_mode").attr("checked",true);
                            $("input:radio[name=modo]").attr("disabled",true);
                        }
                        
                  });
                    {
                        
                     
                    }
                   
                }); //Fin Conf_Graf Click

                //Inicio Gráfico click
               var title;
               var names;

               $("#grafico_a").click(function(){
                    
                     if ($(".param:input[type=checkbox]:checked").length > 0){
                    
                    $("#advertencia_graf").hide();
                    creating = true;
                    
                    $("#grafico").prepend('<div><div id=container'+containerId+ ' class="ui-widget-content container"></div>'+
                    
                                '<button id="closebutton'+containerId+'" title="Eliminar" value="'+containerId+'" class="close_button" ></button>' +
                                
                                '<button id="previewbutton'+containerId+'" title="Vista Previa" value="'+containerId+'" class="print_button" ></button>' +
                                
                                '<button id="savebutton'+containerId+'" title="Guardar" value="'+containerId+'" class="save_button" ></button><div>' +

                                '<div id="comentario'+containerId+'" class="comentario" >' + 

                                '<h3><a href="#">Comentario</a></h3>' +   

                                '<div id="comentario_box'+containerId+'" class="comentario_box">' +

                                    '<form method="post" action="show.php">' + 
                                        '<p>' + 
                                            '<textarea id="comment'+containerId+'" name="content" cols="175" rows="9"></textarea>' +
                                        '</p>' +
                                    '</form>' +
                                '</div> ' +
                                '</div> ' +
                                '<input id="params'+ containerId +'" type="text" value="" style="display:none"/>'
                            );
                            //
                        $("#wrapper").css("height",(100+57*(containerCounter))+"%");
                        $("#menu").css("height",(94+2*containerCounter)+"%");
                                
                                $("#closebutton"+containerId).button({
                                    icons: {
                                        primary: "ui-icon-closethick"
                                    },
                                    text: false
                                    }).click(function(){
                                    
                                    var currentId = $(this).attr("value");
                                     $("#container"+currentId).remove();
                                     $("#comentario"+currentId).remove();
                                     $("#params"+currentId).button().remove();
                                     $("#closebutton"+currentId).button().remove();
                                     $("#previewbutton"+currentId).button().remove();
                                     $("#savebutton"+currentId).button().remove();
                                        
                                    for (var id = currentId; id < containerCounter-1; id++ ){
                                        charts[parseInt(id)+1] = charts[parseInt(id)];
                                        $("#container"+(parseInt(id)+1)).attr("id","container"+id);
                                        $("#comentario"+(parseInt(id)+1)).attr("id","comentario"+id);
                                        $("#comment"+(parseInt(id)+1)).attr("id","comment"+id);
                                        $("#closebutton"+(parseInt(id)+1)).attr("value",id);
                                        $("#previewbutton"+(parseInt(id)+1)).attr("value",id);
                                        $("#savebutton"+(parseInt(id)+1)).attr("value",id);
                                        $("#params"+(parseInt(id)+1)).attr("id","params"+id);
                                        $("#closebutton"+(parseInt(id)+1)).attr("id","closebutton"+id);
                                        $("#previewbutton"+(parseInt(id)+1)).attr("id","previewbutton"+id);
                                        $("#savebutton"+(parseInt(id)+1)).attr("id","savebutton"+id);

                                        }
                                    containerId = containerCounter-1;
                                   
                                    //alert(containerId);
                                    containerCounter--;
                                    if (containerCounter == 0){
                                         $("#wrapper").css("height",(100+57*(containerCounter))+"%");
                                         $("#menu").css("height",(94+2*containerCounter)+"%");
                                    }
                                    else{
                                        $("#wrapper").css("height",(100+57*(containerCounter-1))+"%");
                                        $("#menu").css("height",(94+2*containerCounter-1)+"%");
                                    }
                                    
                                     //alert(containerCounter);
                                   
                                });
                                
                                $("#previewbutton"+containerId).button({
                                    icons: {
                                        primary: "ui-icon-document"
                                    },
                                    text: false
                                    }).click(function(){
                                    
                                    var imageURL = '';
                                    //var svg = charts[$(this).attr("value")]
                                    //alert(charts[$(this).attr("value")].getSVG().toString());
                                    var svg = charts[$(this).attr("value")].getSVG();
                                    canvg(document.getElementById('canvas'), svg);
                                    canvas = document.getElementById('canvas');
                                    var png = canvas.toDataURL("image/png");
                                    //$("canvas").hide();
                                    var text = $("#comment"+$(this).attr("value")).val();
                                    var dataString = 'type=image/png&filename=container'+$(this).attr("value")+'&imagen='+png+'&text='+text;
                                    
                                    $.ajax({
                                           type: 'POST',
                                           data: dataString,
                                           url: server_root+"pdf_informe.php",
                                           async: false,
                                           success: function(data){
                                               imageURL = data;
                                               window.open(imageURL, '_blank', 'fullscreen=yes')
                                            }
                                        });
                                        
                                    });
                                    
                                     
                                    
                                    $("#savebutton"+containerId).button({
                                    icons: {
                                        primary: "ui-icon-disk"
                                    },
                                    text: false
                                    }).click(function(){
                                        var svg = charts[$(this).attr("value")].getSVG();
                                        canvg(document.getElementById('canvas'), svg);
                                        canvas = document.getElementById('canvas');
                                        imagen = canvas.toDataURL("image/png");
                                        comentario = $("#comment"+$(this).attr("value")).val();
                                        parametros = $("#params"+$(this).attr("value")).val();
                                    
                                        $( "#dialog-form-informe" ).dialog( "open" );
                                        
                                        });
                                
                                
                                $("#comentario"+containerId).accordion({
                                        autoHeigth: false,
                                        clearStyle: true,
                                        active: false,
                                        collapsible: true,
                                        speed: 'fast'
                                });
                     
                   
                   names = [];
                   ids = []
                   title = '';
                   sameclassCounter = 0;
                    $(".param:input[type=checkbox]:checked").each(function()
                    {
                        
                        names.push($(this).attr('id'));
                        
                        if ($(this).attr('class').split(" ").length == 3){
                            if (sameclassCounter == $("input."+$(this).attr('class').split(' ')[1]+":checkbox:checked").length - 1){
                                title += ' '+$(this).attr('class').split(" ")[1].toUpperCase()/*.replace("_", " ");*/
                                sameclassCounter = 0;
                            }
                            else{
                                sameclassCounter++;
                            }
                            
                        }else{
                            title += ' '+$(this).attr('id').toString().toUpperCase()/*.replace("_"," ");*/
                        }
                        
                    });

                    var seriesOptions = [];

                    axisIndexes = []            
                    axisCounter = 0,
                    seriesCounter = 0,
                    sameAxisCounter = 0;
                    axisId = 0;
                    colors = Highcharts.getOptions().colors;
                    
                    options = {
                           
                            chart: {},
                            
                            title : {
				text : title
                            },
                            rangeSelector: {
                                selected: 1
                            },
                            credits: {
                              enabled: false  
                            },
                            exporting: {
                                height: 1600,
                                width: 2000,
                                buttons: {
                                    exportButton: {
                                        verticalAlign: 'top',
                                        align: 'right',
                                        y: 40,
                                        x: -10
                                    },

                                    printButton: {
                                        verticalAlign: 'top',
                                        align: 'right',
                                        y: 40,
                                        x: -40
                                        }
                                          }
                            },
                            
                          
                            legend: {
                                align: "right",
                                layout: "vertical",
                                enabled: true,
                                verticalAlign: "middle"
                                
                                /*labelFormatter: function() {
                                    return this.name + ' (T)';
                                }*/

                            },

                            xAxis: {
                                endOnTick: true,
                                showLastLabel: true,
                                type: 'datetime'
                                
                            },

                            yAxis: [
                                
                            ],

                            series: seriesOptions

                            }

                    var jsonURL;
                    
                    $.each(names, function(i, name) {
                        
                        if ($("input:radio[name="+name+"_tipo]:checked").val() == "SPV"){
                            jsonURL = server_root+'info.php?param='+ name.toLowerCase();
                            //$("#inicio").append("<p>"+jsonURL+"</p>");
                            
                            axisIndexes[name] = axisCounter;
                            
                            if (name in indexes){
                                
                            }else{
                                indexes[name] = YAxisLabelsCounter;
                                YAxisLabelsCounter++;
                            
                            $.ajax({
                                  url: jsonURL,
                                  async: false,
                                  dataType: 'json',
                                  success: function (data) {
                                    var array = [];
                                    var valores = String(data).split(",");
                                    array.push(' ');
                                    for (var valor in valores) {
                                        array.push(valores[valor]);
                                    }
                                   
                                    yAxisLabels.push(array);
                                  }
                                });
                            }
                        
                            if ($("#desde").val() && $("#hasta").val()){
                                jsonURL = server_root+'data.php?param='+ name.toLowerCase()+"&tipo=RV&desde="+$("#desde").val()+"&hasta="+$("#hasta").val()+"&modo=normal";
                            }
                            else{
                                jsonURL = server_root+'data.php?param='+ name.toLowerCase()+"&tipo=RV&modo=normal";
                            }
                            
                            
                            if($("#"+name).attr('class').split(" ").length == 3){//SHORTCUT
                                    
                                if (sameAxisCounter == 0 ){
                                        options.yAxis.push( 
                                    {     

                                    title: { text: 'STATE '+'['+$("#"+name).attr('class').split(" ")[1].toUpperCase()+']' },
                                    labels: {
                                        formatter: function() {
                                            return yAxisLabels[indexes[name]][this.value+1];
                                        }
                                    },
                                    offset: 25*(axisCounter+1),
                                    opposite: (axisCounter) % 2 != 0
                                    });
                                }
                                        
                            }
                            else{//NO SHORTCUT
                            options.yAxis.push( 
                            {     
                                    title: { text: 'STATE '+'['+name.toUpperCase()+']' },
                                    labels: {
                                        formatter: function() {
                                            return yAxisLabels[indexes[name]][this.value+1];
                                        }
                                    },
                                    offset: 25*(axisCounter+1),
                                    opposite: (axisCounter) % 2 != 0
                            });
                            }

                        }
                        else{//RPV,OBV,RV
                            axisIndexes[name] = axisCounter;//name a dummy
                            
                            if($("#"+name).attr('class').split(" ").length == 3){//SHORTCUT
                                    
                                if (sameAxisCounter == 0 ){
                                    
                                        options.yAxis.push( 
                                        {  
                                        offset: 25*(axisCounter+1),
                                        endOnTick: true,
                                        opposite: (axisCounter) % 2 != 0,
                                        title: { text: $("#"+name).attr('class').split(" ")[1].toUpperCase()/*.replace("_", " ")*/ }
                                        /*labels: {
                                        formatter: function() {
                                            return this.value;
                                        }
                                        }*/
                                       
                                        });
                                }
                            }
                            else{
                                 options.yAxis.push( //NO SHORTCUT
                                        {    
                                        endOnTick: true,
                                        opposite: (axisCounter) % 2 != 0,
                                        title: { text: name.toUpperCase()/*.replace("_", " ")*/ },
                                        offset: 25*(axisCounter+1)
                                        /*labels: {
                                        formatter: function() {
                                            return this.value;
                                        }
                                        }*/
                                        });
                            }
                            
                         if ($("#desde").val() && $("#hasta").val()){
                                jsonURL = server_root+'data.php?param='+ name.toLowerCase()+"&tipo="+$("input:radio[name="+name+"_tipo]:checked").val()+"&desde="+$("#desde").val()+"&hasta="+$("#hasta").val()+"&modo="+$("input:radio[name=modo]:checked").val();
                            }
                            else{
                                jsonURL = server_root+'data.php?param='+ name.toLowerCase()+"&tipo="+$("input:radio[name="+name+"_tipo]:checked").val()+"&modo="+$("input:radio[name=modo]:checked").val();
                            }
                        }
                        
                        $.ajax({
                                  url: jsonURL,
                                  async: true,
                                  beforeSend: function(){
                                      //alert(containerId);
                                      $("#container"+containerId).html('<img id="loading" src=images/sprites4.gif style="margin-left:38%; margin-top:1%; margin-bottom:1%; position:static; min-width:25%; heigth:20%;"/>');

                                  },
                                  dataType: 'json',
                                  success: function (data) {
                                      
                                        seriesOptions[i] = {
                                        name: name,
                                        data: data,
                                        yAxis: axisIndexes[name],//axisId,
                                        id: axisIndexes[name]//axisId
                                        }
                                        
                                        seriesCounter++;
                                        
                        
                                    if (seriesCounter == names.length) {
                                           
                                            createChart(title);
                                            
                                            containerId++;
                                            containerCounter++;
                                            $("#loading").remove();
                                    }
                                    
                                    
                                
                        
			// As we're loading the data asynchronously, we don't know what order it will arrive. So
			// we keep a counter and create the chart when all the data is loaded.
			
                        //seriesCounter++;
                        
			
                                  }
                                });
                                
                    if($("#"+name).attr('class').split(" ").length == 3 ){//SHORTCUT
                        sameAxisCounter++;
                        if (sameAxisCounter == $("input."+$("#"+name).attr('class').split(' ')[1]+":checkbox:checked").length){
                            axisCounter++
                            sameAxisCounter = 0;
                        }
                    }
                    else{// NO SHORTCUT
                        axisCounter++;
                        }
                    });
                    $("#params"+containerId).val(names.toString());
                    $(".shortcut, .param").removeAttr('checked');
                    $(".shortcut, .param").button('refresh');
                    
                     }
                     else{
                         if (containerCounter > 0 || creating){
                              $("#wrapper").css("height",(100+57*(containerCounter-1))+"%");
                              $("#menu").css("height",(94+3*containerCounter-1)+"%");
                         }
                         else{
                              $("#advertencia_graf").show();
                              $("#wrapper").css("height","100%");
                              $("#menu").css("height","94%");
                         }
                     }
                         
	// create the chart when all data is loaded
                    function createChart(title) {
                         if ( $("input:radio[name=modo]:checked").val() == 'max_min' ){
                                options.chart = {
                                   renderTo : 'container'+containerId,
                                   type: 'columnrange',
                                   borderColor: null,
                                   reflow:true
                                };
                            }
                         else{
                                options.chart =
                                {
                                    renderTo: 'container'+containerId,
                                    borderColor: null,
                                    reflow:true
                                };
                                
                                        options.tooltip = {
                                        shared: true,
                                        useHTML: true,
                                        formatter: function() {

                                                            var s = Highcharts.dateFormat('%A, %b %e, %H:%M:%S', this.x,!1);

                                                            $.each(this.points, function(i, point) {
                                                                
                                                                if (typeof yAxisLabels[indexes[point.series.name]] != "undefined"){

                                                                s += '<br/><span style=color:'+point.series.color+">"+ point.series.name +'</span>:'+
                                                                    '<b>'+yAxisLabels[indexes[point.series.name]][point.y+1]+'</b>';
                                                                }
                                                                else{
                                                                
                                                                s +=   '<br/><span style=color:' + point.series.color + '>'+ point.series.name + '</span>:<b>'+Highcharts.numberFormat(this.y, 2)+'</b>';
                                                                }
                                                            });

                                                            return s;

                                        }
                                    }
                            }
                        cloneToolTip = null;
                        chart = new Highcharts.StockChart(options, function(chart){

                            // apply the date pickers
                            setTimeout(function(){
                                $('input.highcharts-range-selector', $('#'+chart.options.chart.renderTo))
                                    .datepicker()
                            },0)
                            });
                            
                             // Set the datepicker's date format
                            $.datepicker.setDefaults({
                                dateFormat: 'yy-mm-dd',
                                onSelect: function(dateText) {
                                    this.onchange();
                                    this.onblur();
                                }
                            });
                            
                            charts[containerId] = chart;
                            creating = false;
                    }// fin createChart

            });//Fin Gráfico click
          
	}); //Fin Document Ready